<html>
<head>
    <meta charset="utf-8">
    <title>{{$title}}</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=0">
    <link rel="stylesheet" href="/layui/css/layui.css" media="all">
    <!--建议手动加在语言，避免在ie下有时因为加载语言失败导致编辑器加载失败-->
    <!--这里加载的语言文件会覆盖你在配置项目里添加的语言类型，比如你在配置项目里配置的是英文，这里加载的中文，那最后就是中文-->
</head>
<body>
<style>
    .layui-upload-img {
        width: 92px;
        height: 92px;
        margin: 0 10px 10px 0;
    }
</style>
<div class="layui-form" lay-filter="layuiadmin-app-form-list" id="layuiadmin-app-form-list"
     style="padding: 20px 30px 0 0;">
    <div class="layui-form-item">
        <input type="text" name="id" style="display: none" lay-verify="required" placeholder="请输入" autocomplete="off"
               class="layui-input" value="{{$data->id}}">
        <label class="layui-form-label">商品类目</label>
        <div class="layui-input-inline">
            <select name="classify" id="classify" lay-filter="classify">
                @foreach($classify as $k => $v)

                    @if($data->classid == $v['id'])
                        <option selected value="{{$v['id']}}">{{$v['title']}}</option>
                        @else
                        <option value="{{$v['id']}}">{{$v['title']}}</option>
                    @endif
                @endforeach
            </select></div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">属性新增</label>
        <div class="layui-input-inline">
            <select name="keys">

            </select>
        </div>
        <div class="layui-input-inline">
            <input type="text" name="add_value" placeholder="请输入" autocomplete="off" class="layui-input" value="">
        </div>
        <div class="layui-input-inline">
            <button id="add_value" type="button" class="layui-btn">新增</button>
        </div>
    </div>
    <div id="sku"></div>
    <div class="layui-form-item layui-hide">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-submit" id="layuiadmin-app-form-submit"
               value="确认添加">
        <input type="button" lay-submit lay-filter="layuiadmin-app-form-edit" id="layuiadmin-app-form-edit"
               value="确认编辑">
    </div>

</div>
<script src="/layui/layui.js"></script>
<script>
    var data_json = JSON.parse('{!! json_encode($keys) !!}');
    var data_default = JSON.parse('{!! json_encode($default) !!}');
    var data_key = Number('{{$data->classid}}');
    var old_sku = 0;
    layui.config({
        base: '/modules/admin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index', 'form', 'upload', 'sku', 'element'], function () {
        var $ = layui.$
            , form = layui.form
            , upload = layui.upload
            , sku = layui.sku
            , element = layui.element
            , $form = $('.layui-form');

        //监听提交
        form.on('submit(layuiadmin-app-form-edit)', function (data) {
            var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
            var sku = SKU.getData();
            var field = data.field; //获取提交的字段
            field._token = '{{csrf_token()}}';
            // 比较表单是否发生了变化
            if(formIsChange(sku, old_sku)) {
                layer.open({
                title:'提示',
                content: '检测到表单发生了变化，继续提交会清除所有数据',
                icon:5,
                yes:function(layers) {
                    field.sku = sku;
                    //提交 Ajax 成功后，关闭当前弹层并重载表格
                    $.post({
                        url: "{{route('attr.update')}}",
                        data: field,
                        type: "Post",
                        dataType: "json",
                        success: function (data) {
                            //console.log('重载表格');
                            if(data.code == 0){
                                layer.open({
                                    title:'提示',
                                    content:data.msg,
                                    yes:function (layers) {
                                        layer.close(layers);
                                        parent.layer.close(index); //再执行关闭
                                    }
                                });
                            }
                            parent.layer.table.reload('LAY-app-content-list'); //重载表格
                        },
                        error: function (data) {
                            layer.alert('错误', data.msg);
                        }
                    });
                    layer.close(layers);
                }
               })
            } else {
               field.sku_update = sku;
                    $.ajax({
                        url: "{{route('attr.update')}}",
                        data: field,
                        type: "Post",
                        dataType: "json",
                        success: function (data) {
                            //console.log('重载表格');
                            if(data.code == 0){
                                layer.open({
                                    title:'提示',
                                    content:data.msg,
                                    yes:function (layers) {
                                        layer.close(layers);
                                        parent.layer.close(index); //再执行关闭
                                    }
                                });
                            }
                            parent.layui.table.reload('LAY-app-content-list'); //重载表格
                        },
                        error: function (data) {
                            layer.alert('错误', data.msg);
                        }
                    });
            }
        });
        upload.render({
            elem: '#layuiadmin-upload-list'
            , url: '/upload'
            , accept: 'images'
            , method: 'post'
            , acceptMime: 'image/*'
            , done: function (res) {
                $("input[name='images_url']").val(res.data.src);
                $('#demo1').attr('src', res.data.src);
            }
        });
        $("#sku").empty();
        if (data_key) {
            item = data_json[data_key];
        } else {
            item = data_json["{{isset($classify[0]['id'])?$classify[0]['id']:''}}"];
        }
        $.each(item, function (ka, va) {
            //console.log(va.name);
            appendOptionTo($form.find('select[name=keys]'), va.name, va.id, null);
        });
        form.render();
        data = data_default;
        var SKU = sku.init({id: 'sku', item: item, data: data});
        form.on('select(classify)', function (data) {
            var key = data.value;
            $("#sku").empty();
            $form.find('select[name=keys]').html("");
            item = data_json[key];
            if (key == data_key) {
                data = data_default;
            } else {
                data = [];
            }
            $.each(item, function (ka, va) {
                appendOptionTo($form.find('select[name=keys]'), va.name, va.id, null);
            });
            form.render();
            SKU = sku.init({id: 'sku', item: item, data: data});
        });

        function appendOptionTo($o, k, v, d) {
            var $opt = $("<option>").text(k).val(v);
            if (v == d) {
                $opt.attr("selected", "selected")
            }
            $opt.appendTo($o);
        }

        $('#add_value').on('click', function () {
            var value = $("input[name='add_value']").val();
            var keys = $("select[name='keys']").val();
            var token = '{{csrf_token()}}';
            if (!value) {
                layer.msg('请输入需新增的属性值', {
                    offset: '15px'
                    , icon: 5
                    , time: 1000
                    , anim: 6
                });
            }
            $.ajax({
                url: "{{route('attr.value_add')}}",
                data: {keys: keys, title: value, _token: token},
                type: "Post",
                dataType: "json",
                success: function (data) {
                    if (data.code == 0) {
                        skuReset(data.data, keys);
                    } else {
                        layer.msg(data.msg, {
                            offset: '15px'
                            , icon: 5
                            , time: 1000
                            , anim: 6
                        });
                    }
                },
                error: function (data) {
                    layer.msg('网络错误', {
                        offset: '15px'
                        , icon: 5
                        , time: 1000
                        , anim: 6
                    });
                }
            });
        });

        function skuReset(id, keys) {
            var item = SKU.getItem();
            var data = SKU.getData();
            var add = {id: id.id, name: id.title};
            $.each(item, function (ka, va) {
                if (keys == va.id) {
                    item[ka]['sub'].push(add);
                }
            })
            $("#sku").empty();
            SKU = sku.init({id: 'sku', item: item, data: data});
        }

        $(document).on('click', '.layui-btn-normal', function(){
            var index = parent.layer.getFrameIndex(window.name);
            console.log(index);
            var data = $(this).siblings('input[data-type=material]').val();
            var sku_id = $(this).siblings();
            sku_id = $(this).attr('data-id');
            // 判断是否设置了sku
            if(sku_id > 0){
                layer.open({
                    type: 2,
                    title: '材料',
                    content: '/goods-sku/' + sku_id + '/material',
                    area: ['1080px', '500px'],
                    yes: function (index) {
                        layer.close(index);
                    }
                });
            } else {
                layer.msg('目前仅支持设置好sku后再绑定材料');
            }

        });

        var test = 'test';
//获取子页面传入的数据
 function GetChildValue(obj){
   test = obj;
 }
        // 材料按钮
        // $('td').on('click','.layui-btn-normal', function () {
        //     var data = $(this).siblings('input[data-type=material]').val();
        //     var sku_id = $(this).siblings();
        //     sku_id = $(this).attr('data-id');
        //     layer.open({
        //         type: 2,
        //         title: '材料',
        //         content: '/goods-sku/' + sku_id + '/material',
        //         area: ['1080px', '500px'],
        //         yes: function (index) {
        //             layer.close(index);
        //         }
        //     });
        // });

        // 比较表单是否发生了变化
        function formIsChange(sku, old_sku)
        {
            var old_sku_id = [];
            for(var i in old_sku){
                old_sku_id.push(old_sku[i]['id'])
            }
            // 判断表单数据是否发生了变化
            var temp = 0;
            for(var i in sku){
                if(!in_array(sku[i]['id'], old_sku_id)){
                    return true;
                }
            }

            return false;
        }

        function in_array(value, array)
        {
            for(var i in array){
                if(array[i] == value){
                    return true;
                }
            }

            return false;
        }

        old_sku = SKU.getData();
    })
</script>
</body>
</html>
